package org.szy.plugin.sys.service.impl;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.ProxyComponent;
import org.szy.core.common.service.impl.BaseServiceImpl;
import org.szy.plugin.sys.entity.SysUserRole;
import org.szy.plugin.sys.mapper.SysUserRoleMapper;
import org.szy.plugin.sys.param.SysUserRoleAddParam;
import org.szy.plugin.sys.service.SysUserRoleService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.szy.plugin.sys.entity.table.SysUserRoleTableDef.SYS_USER_ROLE;

/**
 * 用户和角色关联Service接口实现类
 *
 * @author wangbuhao
 * @since 2023-06-27 09:56:03
 **/
@ProxyComponent
public class SysUserRoleServiceImpl extends BaseServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Inject
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public List<SysUserRole> listByUserId(Long userId) {
        return list(SYS_USER_ROLE.USER_ID.eq(userId));
    }

    @Override
    public boolean add(SysUserRoleAddParam param) {
        Long userId = Convert.toLong(param.getUserId());
        boolean remove = remove(SYS_USER_ROLE.USER_ID.eq(userId));

        if (StrUtil.isNotEmpty(param.getRoleJson())) {
            List<Map> maps = JSONUtil.toList(param.getRoleJson(), Map.class);
            List<SysUserRole> list = new ArrayList<>(maps.size());
            for (Map map : maps) {
                list.add(new SysUserRole(userId, Convert.toLong(map.get("roleId")), Convert.toStr(map.get("roleName"))));
            }
            return saveBatch(list);
        }

        return remove;
    }
}
